<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>shiro(一) 介绍与入门 | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="安全">
    <meta name="description" content="学习来源：Apache Shiro IntroductionWhat is Apache Shiro?Apache Shiro是一个功能强大、灵活的，开源的安全框架。它可以干净利落地处理身份验证、授权、企业会话管理和加密。 What can Shiro do? 验证用户身份 用户访问权限控制，比如： 判断用户是否分配了一定的安全角色。 判断用户是否被授予完成某个操作的权限   在非 web 或 E">
<meta name="keywords" content="安全">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro(一) 介绍与入门">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/12/05/shiro01/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="学习来源：Apache Shiro IntroductionWhat is Apache Shiro?Apache Shiro是一个功能强大、灵活的，开源的安全框架。它可以干净利落地处理身份验证、授权、企业会话管理和加密。 What can Shiro do? 验证用户身份 用户访问权限控制，比如： 判断用户是否分配了一定的安全角色。 判断用户是否被授予完成某个操作的权限   在非 web 或 E">
<meta property="og:image" content="http://magic_duck.oschina.io/image/shiro_Features.png">
<meta property="og:updated_time" content="2017-12-05T09:59:31.056Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro(一) 介绍与入门">
<meta name="twitter:description" content="学习来源：Apache Shiro IntroductionWhat is Apache Shiro?Apache Shiro是一个功能强大、灵活的，开源的安全框架。它可以干净利落地处理身份验证、授权、企业会话管理和加密。 What can Shiro do? 验证用户身份 用户访问权限控制，比如： 判断用户是否分配了一定的安全角色。 判断用户是否被授予完成某个操作的权限   在非 web 或 E">
<meta name="twitter:image" content="http://magic_duck.oschina.io/image/shiro_Features.png">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">shiro(一) 介绍与入门</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">shiro(一) 介绍与入门</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-12-04T16:00:00.000Z" itemprop="datePublished" class="page-time">
  2017-12-05
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Introduction"><span class="post-toc-number">1.</span> <span class="post-toc-text">Introduction</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#What-is-Apache-Shiro"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">What is Apache Shiro?</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#What-can-Shiro-do"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">What can Shiro do?</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Apache-Shiro-Features-特性"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">Apache Shiro Features 特性</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Your-First-Apache-Shiro-Application"><span class="post-toc-number">2.</span> <span class="post-toc-text">Your First Apache Shiro Application</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#environment-环境"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">environment 环境</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Enable-Shiro-使用"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">Enable Shiro 使用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Configuration-配置"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">Configuration 配置</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Referencing-the-Configuration-引用配置"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">Referencing the Configuration 引用配置</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Using-Shiro-使用"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">Using Shiro 使用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Final-Tutorial-class"><span class="post-toc-number">2.6.</span> <span class="post-toc-text">Final Tutorial class</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">总结</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-shiro01"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">shiro(一) 介绍与入门</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年12月05日 0:00" datetime="2017-12-04T16:00:00.000Z"  itemprop="datePublished">2017-12-05</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>学习来源：<strong><a href="http://shiro.apache.org/introduction.html" target="_blank" rel="external">Apache Shiro</a></strong></p>
<h2 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h2><h3 id="What-is-Apache-Shiro"><a href="#What-is-Apache-Shiro" class="headerlink" title="What is Apache Shiro?"></a>What is Apache Shiro?</h3><p>Apache Shiro是一个功能强大、灵活的，开源的安全框架。它可以干净利落地处理身份验证、授权、企业会话管理和加密。</p>
<h3 id="What-can-Shiro-do"><a href="#What-can-Shiro-do" class="headerlink" title="What can Shiro do?"></a>What can Shiro do?</h3><ul>
<li>验证用户身份</li>
<li>用户访问权限控制，比如：<ul>
<li>判断用户是否分配了一定的安全角色。</li>
<li>判断用户是否被授予完成某个操作的权限</li>
</ul>
</li>
<li>在非 web 或 EJB 容器的环境下可以任意使用Session API</li>
<li>可以响应认证、访问控制，或者 Session 生命周期中发生的事件</li>
<li>可将一个或以上用户安全数据源数据组合成一个复合的用户 “view”(视图)</li>
<li>支持单点登录(SSO)功能</li>
<li>支持提供“Remember Me”服务，获取用户关联信息而无需登录</li>
<li>…</li>
</ul>
<h3 id="Apache-Shiro-Features-特性"><a href="#Apache-Shiro-Features-特性" class="headerlink" title="Apache Shiro Features 特性"></a>Apache Shiro Features 特性</h3><p>Apache Shiro是一个全面的、蕴含丰富功能的安全框架。下图为描述Shiro功能的框架图：</p>
<p><img src="/image/shiro_Features.png" alt="1"></p>
<p>以下是Shiro框架的开发团队称为应用安全的四大基石：</p>
<ul>
<li><strong>Authentication(认证)：</strong> 用户身份识别，通常被称为用户’登录’</li>
<li><strong>Authorization(授权)：</strong> 访问控制，比如某个用户是否具有某个操作的使用权限</li>
<li><strong>Session Management(会话管理)：</strong> 特定于用户的会话管理，甚至在非web 或 EJB 应用程序。</li>
<li><strong>Cryptography(加密)：</strong> 在对数据源使用加密算法加密的同时，保证易于使用。</li>
</ul>
<p>还有其他的功能来支持和加强这些不同应用环境下安全领域的关注点：</p>
<ul>
<li>Web支持：Shiro提供的web支持api，可以很轻松的保护web 应用程序的安全。</li>
<li>缓存：缓存是 Apache Shiro 保证安全操作快速、高效的重要手段。</li>
<li>并发：Apache Shiro 支持多线程应用程序的并发特性。</li>
<li>测试：支持单元测试和集成测试，确保代码和预想的一样安全。</li>
<li>“Run As”：这个功能允许用户假设另一个用户的身份(在许可的前提下)。</li>
<li>“Remember Me”：跨 session 记录用户的身份，只有在强制需要时才需要登录。</li>
</ul>
<hr>
<h2 id="Your-First-Apache-Shiro-Application"><a href="#Your-First-Apache-Shiro-Application" class="headerlink" title="Your First Apache Shiro Application"></a>Your First Apache Shiro Application</h2><h3 id="environment-环境"><a href="#environment-环境" class="headerlink" title="environment 环境"></a>environment 环境</h3><p>本文使用Maven作为我们的构建工具，因此你应该先学会使用Maven，首先准备依赖环境：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 添加junit、common-logging及shiro-core依赖即可 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;junit.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-logging<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;commons.logging.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.shiro<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>shiro-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>  </div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;shiro.core.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span>  </div><div class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span>  </div><div class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="Enable-Shiro-使用"><a href="#Enable-Shiro-使用" class="headerlink" title="Enable Shiro 使用"></a>Enable Shiro 使用</h3><p>现在有必要让你提前知道Shrio SecurityManager是程序中Shiro的核心，每一个程序都必定会存在一个SecurityManager，所以，在我们这个示例程序中必须做的第一件事情是建立一个SecurityManager实例。</p>
<h3 id="Configuration-配置"><a href="#Configuration-配置" class="headerlink" title="Configuration 配置"></a>Configuration 配置</h3><p>在这之前，我们还得提一点，在Java代码中对Shiro的SecurityManager所须的选项和内部组件进行配置会让人感觉有点小痛苦，所以Shiro默认提供了一个基于ini配置文件的解决方案，下面我们就动手在src/main/resources目录下创建一个<strong>shiro.ini</strong>配置文件来配置SecurityManager：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># ======================================================</span></div><div class="line"><span class="comment"># Shiro INI configuration</span></div><div class="line"><span class="comment">#</span></div><div class="line"><span class="comment"># Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :)</span></div><div class="line"><span class="comment"># ======================================================</span></div><div class="line"></div><div class="line"><span class="comment"># ------------------------------------------------------</span></div><div class="line"><span class="comment"># Users and their (optional) assigned roles</span></div><div class="line"><span class="comment"># username = password, role1, role2, ..., roleN</span></div><div class="line"><span class="comment"># ------------------------------------------------------</span></div><div class="line"><span class="section">[users]</span></div><div class="line"><span class="attr">root</span> = secret, admin</div><div class="line"><span class="attr">guest</span> = guest, guest</div><div class="line"><span class="attr">presidentskroob</span> = <span class="number">12345</span>, president</div><div class="line"><span class="attr">darkhelmet</span> = ludicrousspeed, darklord, schwartz</div><div class="line"><span class="attr">lonestarr</span> = vespa, goodguy, schwartz</div><div class="line"></div><div class="line"><span class="comment"># ------------------------------------------------------</span></div><div class="line"><span class="comment"># Roles with assigned permissions</span></div><div class="line"><span class="comment"># roleName = perm1, perm2, ..., permN</span></div><div class="line"><span class="comment"># ------------------------------------------------------</span></div><div class="line"><span class="section">[roles]</span></div><div class="line"><span class="attr">admin</span> = *</div><div class="line"><span class="attr">schwartz</span> = lightsaber:*</div><div class="line"><span class="attr">goodguy</span> = winnebago:drive:eagle5</div></pre></td></tr></table></figure>
<p>在上面的配置中，[users]和[roles]定义了用户和角色，这会在下面的测试代码中用到。</p>
<p>在[users]下，lonestarr = vespa, goodguy, schwartz代表的意义是：用户lonestarr的凭证（密码）是vespa，该用户含有goodguy和schwartz这两个角色。</p>
<p>在[roles]下，goodguy = winnebago:drive:eagle5代表的意义是：允许角色goodguy对类型为winnebago的实体eagle5执行drive操作。</p>
<h3 id="Referencing-the-Configuration-引用配置"><a href="#Referencing-the-Configuration-引用配置" class="headerlink" title="Referencing the Configuration 引用配置"></a>Referencing the Configuration 引用配置</h3><p>下面我们可以在我们的示例程序中创建SecurityManager实例了，在src/main/java下创建<strong>Tutorial.java</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Tutorial</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Logger log = Logger.getLogger(<span class="string">"SecurityManagerTest"</span>);</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        log.info(<span class="string">"My First Apache Shiro Application"</span>);</div><div class="line">        </div><div class="line">        <span class="comment">// 1、使用 Shiro的IniSecurityManagerFactory加载了shiro.ini文件件</span></div><div class="line">        Factory&lt;org.apache.shiro.mgt.SecurityManager&gt; factory = <span class="keyword">new</span> IniSecurityManagerFactory(<span class="string">"classpath:shiro.ini"</span>);</div><div class="line">        </div><div class="line">        <span class="comment">// 2、分析INI文件并根据配置文件返回一个SecurityManager实例，并绑定给SecurityUtils</span></div><div class="line">        SecurityManager securityManager = factory.getInstance();</div><div class="line">        SecurityUtils.setSecurityManager(securityManager);</div><div class="line">        </div><div class="line">        System.exit(<span class="number">0</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="Using-Shiro-使用"><a href="#Using-Shiro-使用" class="headerlink" title="Using Shiro 使用"></a>Using Shiro 使用</h3><p>现在我们的SecurityManager已经准备好了，我们可以开始进行我们真正关心的事情–执行安全操作了。</p>
<p>通常我们会在写代码或者设计用户接口的时候问这些问题：程序通常建立在用户基础上，程序功能展示（和安全）也基于每一个用户。所以，通常我们考虑我们程序安全的方法也建立在当前用户的基础上，Shiro 的 API 提供了’the current user’概念，即 Subject。</p>
<p>在几乎所有的环境中，你可以通过如下语句得到当前用户的信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Subject currentUser = SecurityUtils.getSubject();</div></pre></td></tr></table></figure>
<p>使用这个方法我们可以获取当前执行的Subject，Subject是一个安全术语意思是“当前运行用户的指定安全视图（a security-specific view of the currently executing user）” ，在安全认证中，“Subject”可以认为是一个人，也可以认为是第三方进程、时钟守护任务、守护进程帐户或者其它。它可简单描述为“当前和软件进行交互的事件”，在大多数情况下，你可以认为它是一个“人（User）”。</p>
<p>如果你针对该用户希望一些事情在程序当前会话期内可行，你可以获取他们的 session：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Session session = currentUser.getSession();</div><div class="line">session.setAttribute( <span class="string">"someKey"</span>, <span class="string">"aValue"</span> );</div></pre></td></tr></table></figure>
<p>Session是shiro指定的一个实例，提供基本上所有HttpSession的功能，但具备额外的好处和不同：它不需要一个HTTP环境！如果发布到一个web程序中，默认情况下 Session将会使用HttpSession作为基础，但是，在一个非web程序中，Shiro将自动默认使用它的Enterprise Session Management，这意味着你可以在任何程序中使用相同的API，而根本不需要考虑发布环境！</p>
<p>现在你可以获取一个Subject和它们的Session，真正填充有用的代码如检测其是否被允许做某些事情如何？比如检查其角色和权限？我们只能对一个已知用户做这些检测，如上我们获取Subject实例表示当前用户，但是当前用户是认证，嗯，他们是任何人–直到他们至少登录一次，我们现在就做这件事情：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> ( !currentUser.isAuthenticated() ) &#123;</div><div class="line">    <span class="comment">//收集用户的主要信息和凭据，来自GUI中的特定的方式</span></div><div class="line">    <span class="comment">//如包含用户名/密码的HTML表格，X509证书，OpenID，等。</span></div><div class="line">    <span class="comment">//我们将使用用户名/密码的例子因为它是最常见的。.</span></div><div class="line">    UsernamePasswordToken token = <span class="keyword">new</span> UsernamePasswordToken(<span class="string">"lonestarr"</span>, <span class="string">"vespa"</span>);</div><div class="line"></div><div class="line">    <span class="comment">//支持'remember me' (无需配置，内建的!):</span></div><div class="line">    token.setRememberMe(<span class="keyword">true</span>);</div><div class="line"></div><div class="line">    currentUser.login(token);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>　<br>如果登录失败了，你可以捕获所有异常按你的期望方式去处理，shiro提供了许多不同类型的异常(<a href="https://shiro.apache.org/static/1.3.2/apidocs/org/apache/shiro/authc/AuthenticationException.html" target="_blank" rel="external">详情点我</a>)，当然也可以抛出你自己的异常：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">try</span> &#123;</div><div class="line">    currentUser.login( token );</div><div class="line">    <span class="comment">//无异常，说明就是我们想要的!</span></div><div class="line">&#125; <span class="keyword">catch</span> ( UnknownAccountException uae ) &#123;</div><div class="line">    <span class="comment">//username 不存在，给个错误提示?</span></div><div class="line">&#125; <span class="keyword">catch</span> ( IncorrectCredentialsException ice ) &#123;</div><div class="line">    <span class="comment">//password 不匹配，再输入?</span></div><div class="line">&#125; <span class="keyword">catch</span> ( LockedAccountException lae ) &#123;</div><div class="line">    <span class="comment">//账号锁住了，不能登入。给个提示?</span></div><div class="line">&#125; </div><div class="line">    ... 更多类型异常 ...</div><div class="line">&#125; <span class="keyword">catch</span> ( AuthenticationException ae ) &#123;</div><div class="line">    <span class="comment">//未考虑到的问题 - 错误?</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>到目前为止，我们有了一个登录用户，接下来我们能做什么？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 让我们显示他们是谁</span></div><div class="line">log.info( <span class="string">"User ["</span> + currentUser.getPrincipal() + <span class="string">"] logged in successfully."</span> );</div><div class="line"><span class="comment">// 我们也可以判断他们是否拥有某个角色：</span></div><div class="line"><span class="keyword">if</span> ( currentUser.hasRole( <span class="string">"schwartz"</span> ) ) &#123;</div><div class="line">    log.info(<span class="string">"May the Schwartz be with you!"</span> );</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    log.info( <span class="string">"Hello, mere mortal."</span> );</div><div class="line">&#125;</div><div class="line"><span class="comment">// 我们也可以判断他们是否拥有某个特定动作或入口的权限：</span></div><div class="line"><span class="keyword">if</span> ( currentUser.isPermitted( <span class="string">"lightsaber:weild"</span> ) ) &#123;</div><div class="line">    log.info(<span class="string">"You may use a lightsaber ring.  Use it wisely."</span>);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    log.info(<span class="string">"Sorry, lightsaber rings are for schwartz masters only."</span>);</div><div class="line">&#125;</div><div class="line"><span class="comment">// 同样，我们还可以执行非常强大的 instance-level （实例级别）的权限检测，检测用户是否具备访问某个类型特定实例的权限：</span></div><div class="line"><span class="keyword">if</span> ( currentUser.isPermitted( <span class="string">"winnebago:drive:eagle5"</span> ) ) &#123;</div><div class="line">    log.info(<span class="string">"You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'.  "</span> +</div><div class="line">                <span class="string">"Here are the keys - have fun!"</span>);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    log.info(<span class="string">"Sorry, you aren't allowed to drive the 'eagle5' winnebago!"</span>);</div><div class="line">&#125;</div><div class="line"><span class="comment">// 最后，当用记不再使用系统，可以退出登录：</span></div><div class="line">currentUser.logout(); <span class="comment">//清除识别信息，设置 session 失效.</span></div></pre></td></tr></table></figure>
<h3 id="Final-Tutorial-class"><a href="#Final-Tutorial-class" class="headerlink" title="Final Tutorial class"></a>Final Tutorial class</h3><p>下面贴出完整代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">    log.info(<span class="string">"My First Apache Shiro Application"</span>);</div><div class="line"></div><div class="line">    Factory&lt;org.apache.shiro.mgt.SecurityManager&gt; factory = <span class="keyword">new</span> IniSecurityManagerFactory(<span class="string">"classpath:shiro.ini"</span>);</div><div class="line">    SecurityManager securityManager = factory.getInstance();</div><div class="line">    SecurityUtils.setSecurityManager(securityManager);</div><div class="line"></div><div class="line">    <span class="comment">// 获取当前执行用户:</span></div><div class="line">    Subject currentUser = SecurityUtils.getSubject();</div><div class="line"></div><div class="line">    <span class="comment">// 做点跟 Session 相关的事</span></div><div class="line">    Session session = currentUser.getSession();</div><div class="line">    session.setAttribute(<span class="string">"someKey"</span>, <span class="string">"aValue"</span>);</div><div class="line">    String value = (String) session.getAttribute(<span class="string">"someKey"</span>);</div><div class="line">    <span class="keyword">if</span> (value.equals(<span class="string">"aValue"</span>)) &#123;</div><div class="line">        log.info(<span class="string">"Retrieved the correct value! ["</span> + value + <span class="string">"]"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 登录当前用户检验角色和权限</span></div><div class="line">    <span class="keyword">if</span> (!currentUser.isAuthenticated()) &#123;</div><div class="line">        UsernamePasswordToken token = <span class="keyword">new</span> UsernamePasswordToken(<span class="string">"lonestarr"</span>, <span class="string">"vespa"</span>);</div><div class="line">        token.setRememberMe(<span class="keyword">true</span>);</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            currentUser.login(token);</div><div class="line">        &#125; <span class="keyword">catch</span> (UnknownAccountException uae) &#123;</div><div class="line">            log.info(<span class="string">"There is no user with username of "</span> + token.getPrincipal());</div><div class="line">        &#125; <span class="keyword">catch</span> (IncorrectCredentialsException ice) &#123;</div><div class="line">            log.info(<span class="string">"Password for account "</span> + token.getPrincipal() + <span class="string">" was incorrect!"</span>);</div><div class="line">        &#125; <span class="keyword">catch</span> (LockedAccountException lae) &#123;</div><div class="line">            log.info(<span class="string">"The account for username "</span> + token.getPrincipal() + <span class="string">" is locked.  "</span></div><div class="line">                    + <span class="string">"Please contact your administrator to unlock it."</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// ... 捕获更多异常</span></div><div class="line">        <span class="keyword">catch</span> (AuthenticationException ae) &#123;</div><div class="line">            <span class="comment">// 无定义?错误?</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 说出他们是谁:</span></div><div class="line">    log.info(<span class="string">"User ["</span> + currentUser.getPrincipal() + <span class="string">"] logged in successfully."</span>);</div><div class="line"></div><div class="line">    <span class="comment">// 测试角色</span></div><div class="line">    <span class="keyword">if</span> (currentUser.hasRole(<span class="string">"schwartz"</span>)) &#123;</div><div class="line">        log.info(<span class="string">"May the Schwartz be with you!"</span>);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        log.info(<span class="string">"Hello, mere mortal."</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 测试一个权限 (非（instance-level）实例级别)</span></div><div class="line">    <span class="keyword">if</span> (currentUser.isPermitted(<span class="string">"lightsaber:weild"</span>)) &#123;</div><div class="line">        log.info(<span class="string">"You may use a lightsaber ring.  Use it wisely."</span>);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        log.info(<span class="string">"Sorry, lightsaber rings are for schwartz masters only."</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 一个(非常强大)的实例级别的权限:</span></div><div class="line">    <span class="keyword">if</span> (currentUser.isPermitted(<span class="string">"winnebago:drive:eagle5"</span>)) &#123;</div><div class="line">        log.info(<span class="string">"You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "</span></div><div class="line">                + <span class="string">"Here are the keys - have fun!"</span>);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        log.info(<span class="string">"Sorry, you aren't allowed to drive the 'eagle5' winnebago!"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 退出登录</span></div><div class="line">    currentUser.logout();</div><div class="line"></div><div class="line">    System.exit(<span class="number">0</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>这个示例能帮助你理解Shiro的设计理念，Subject和SecurityManager。但他还是太过简单了，你可以会问自己：如果我不想使用INI用户账号，而希望连接更复杂的用户数据源呢？ 要解决这些问题，需要更深入地了解并理解Shiro的架构和配置机制，我们将在下一节中介绍。</p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T09:59:31.056Z" itemprop="dateUpdated">2017年12月5日 17:59</time>
</span><br>


        如要转载请注明出处：<a href="/2017/12/05/shiro01/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/12/05/shiro01/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/安全/">安全</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/12/05/shiro01/&title=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/12/05/shiro01/&title=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/12/05/shiro01/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/12/05/shiro01/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/12/05/shiro01/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/12/05/shiro02/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">shiro(二) 架构和配置</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/11/27/tomcat_managerServlet/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">tomcat ManagerServlet阅读源码后的实践</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/12/05/shiro01/&title=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/12/05/shiro01/&title=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/12/05/shiro01/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《shiro(一) 介绍与入门》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/12/05/shiro01/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/12/05/shiro01/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/12/05/shiro01/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
